package com.way2sms.way2inbox;

/**
 * Created by sys2034 on 23/12/14.
 */

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.app.NotificationManager;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import www.way2inbox.common.Constants;
import www.way2inbox.common.PrintMsg;
import www.way2inbox.data.Native_DatabaseHelper;
import www.way2inbox.data.smsfetch;
import www.way2inbox.settings.ApplicationConstants;


public class SmsReceiver extends BroadcastReceiver {
    public SmsReceiver() {
    }
    String[] ProcessMessage;
    String SenderMessage;
    Native_DatabaseHelper smsDb;
Context context1;
    public boolean isAlpha(String name) {
        return name.matches("[0-9+]+");
    }
    private static final String TAG = "SmsReceiver";
    String SMSReceiver="android.provider.Telephony.SMS_RECEIVED";

    //settings values
    boolean notificationstatus,popup_status,vibrate_status,wakeup_status;
    String vibrate_pattern,ringtonepath;
    PowerManager.WakeLock wakeLock;
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG,"OnReceive ++>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        context1=context;

      notificationstatus=getPrefKeyValues(ApplicationConstants.SettingsPreferenceKeys.NOTIFICATION);
      popup_status=getPrefKeyValues(ApplicationConstants.SettingsPreferenceKeys.POPUP_WINDOW);
      wakeup_status=getPrefKeyValues(ApplicationConstants.SettingsPreferenceKeys.WAKEUP_SCREEN);

        vibrate_pattern=getPrefKeyValues1(ApplicationConstants.SettingsPreferenceKeys.VIBRATE_PATTERN);
        ringtonepath=getPrefKeyValues1(ApplicationConstants.SettingsPreferenceKeys.RINGTONE);
        if(wakeup_status){
            System.out.println("wakeup status is true ");
            PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
             wakeLock = powerManager.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire();
            new Handler().postDelayed(new Runnable() {
                // Using handler with postDelayed called runnable run method
                @Override
                public void run() {
                    wakeLock.release();
                }
            }, 2 * 1000);
        }
        //DUE TO TWO RECEIVER , CONDITION IS FOR ONLY SMS REVEIVED ..
        if(intent.getAction().toString().equalsIgnoreCase(SMSReceiver)) {
            smsDb = new Native_DatabaseHelper(context);
//        smsDb.on
            sh = context.getSharedPreferences("notificationid", 0);
            try {
                Log.i(TAG, "OnReceive ++>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>1");
                Bundle bndl = intent.getExtras();
                SmsMessage[] msg = null;
                String str = "";
                if (null != bndl) {
                    Log.i(TAG, "OnReceive ++>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>2 " + intent.getAction().toString());
                    //---retrieve the SMS message received---
                    Object[] pdus = (Object[]) bndl.get("pdus");
                    msg = new SmsMessage[pdus.length];
                    for (int i = 0; i < msg.length; i++) {
                        msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
//                    str += "SMS From " + msg[i].getOriginatingAddress();
//                    str += " :\r\n";
//                    str += msg[i].getMessageBody().toString();
//                    str += "\n";
//                    Log.i(TAG,"OnReceive ++>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>3");
//                    //---display incoming SMS as a Android Toast---
//                    Toast.makeText(context, str, Toast.LENGTH_SHORT).show();


                        String sender = msg[i].getOriginatingAddress();
                        PrintMsg.SetToast(context, "incoming message :\n" + sender, 0);


                        //AUTO VERIFICATION CODE and READ ALL WAY2SMS MESSAGES FOR THE APPLICATION FROM INCOMING SMS..
                        if (sender.contains("-WAYSMS")) {
                            String body = msg[i].getMessageBody().toString();
                            Log.i(TAG, "OnReceive ++>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>5 " + body);
                            //SENDING CODE TO STARTUP PAGE EDITTEXT FEILD..
                            if (body.contains("Your Way2SMS.com Account ")) {
                                ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
                                List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
                                ComponentName componentInfo = taskInfo.get(0).topActivity;
                                if (componentInfo.getClassName().equalsIgnoreCase("com.way2sms.way2inbox.Startup") ) {
                                    body = body.replaceAll("Password: ", "Password:");
                                    String[] code = body.split("Password:");
                                    Log.i(TAG, "OnReceive ++>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>6 " + code[1]);
                                    Log.e("SMS READER", "GOt Way2sms SMS " + code[1]);
                                    // A custom Intent that will used as another Broadcast
                                    Intent in = new Intent("SmsMessage.intent.MAIN").putExtra(
                                            "get_msg", code[1]);

                                    // You can place your check conditions here(on the SMS or the
                                    // sender)
                                    // and then send another broadcast
                                    context.sendBroadcast(in);
                                }
                            }

//                            String[] Number = body.split(":");
//                            if (Number[0] != null && Number[0].length() > 9 && isAlpha(Number[0])) {
//                                if (Number[1].contains("Reply via WAY2SMS")) {
//                                    ProcessMessage = Number[1].split("-");
//
//                                    //ACTUAL MESSAGE HERE... AFTER SPLITTING
//                                    SenderMessage = ProcessMessage[0];

                                    TriggerPushNotif(context,sender, body);
//                                }
//                            }

                        } else {
                            TriggerPushNotif(context, sender, msg[i].getMessageBody().toString());

                        }


//                NOTIFICATION_ID=idpreference.getInt("count", 0);
//                NOTIFICATION_ID++;
//                insertId(NOTIFICATION_ID, "count");
//                displayNotificationOne(context,displayname, sender, NOTIFICATION_ID,msg[i].getMessageBody().toString());

                    }
                }
            } catch (Exception e) {
                Log.e("SMS", "Exception: " + e);
            }
        }
    }


    SharedPreferences SH_notif;
    SharedPreferences.Editor sh_editor;
    public void TriggerPushNotif(Context context,String senderNum,String message){
        try {
            // NEED TO CHECK WITH SETTINGS..
            SH_notif =context.getSharedPreferences("ChatRoomNumber", 0);
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            if (currentapiVersion >= Build.VERSION_CODES.KITKAT){
                // Do something for KITKAT and above versions
                ContentValues values = new ContentValues();
                values.put("address", senderNum);
                values.put("body", message);
                values.put("read", "0");
                values.put("date", System.currentTimeMillis());
                context.getContentResolver().insert(
                        Uri.parse("content://sms/inbox"), values);
            }



            ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (!componentInfo.getClassName().equals("com.way2sms.way2inbox.Messages") && smsDb.getCount(senderNum)==0 && notificationstatus){
                Log.i(TAG, "NOT IN MESSAGE ");
                if(!senderNum.contains(SH_notif.getString("ChatNO", "XXXX"))){
                    Log.i(TAG, "NOT SAME NUMBER IN CHATROOM "+SH_notif.getString("ChatNO","XXXX")+"---->sender :"+senderNum);
                    smsDb.insertPush(getContactName(senderNum), senderNum, message, String.valueOf(System.currentTimeMillis()));
                    displayNotification(context);
                   // ringtone();
                }else{
                    //PLAY MUSIC AND UPDATE THE ADAPTER..
                    Log.i(TAG, "SAME NUMBER IN CHATROOM");
                    sendResultMessage(5);
                }
             }else if(smsDb.getTypeCount(senderNum,"2")!=0 && notificationstatus){
                displayNotificationPrivate(context);
               // ringtone();
            } else{
                
                //SET SOUND AND UPDATE THE MESSAGE CLASS ADAPTER..

                Log.i(TAG, "IN MESSAGE CLASS");
                sendResultMessage(3);
            }




        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @SuppressLint("NewApi")
    private void displayNotificationPrivate(Context context) {

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                context);
        mBuilder.setContentTitle("Way2Inbox");
        mBuilder.setContentText("got a private message");
        mBuilder.setSmallIcon(R.drawable.ic_launcher);
        mBuilder.setAutoCancel(true);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(Messages.class);
        resultIntent=new Intent(context, PrivateSMS.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(1,
                PendingIntent.FLAG_ONE_SHOT);
        mBuilder.setContentIntent(resultPendingIntent);
        if(vibrate_status){
            mBuilder.setVibrate(new long[]{1000,1000,1000,1000});
        }
        myNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        myNotificationManager.notify(1, mBuilder.build());
    }




    NotificationCompat.Builder builder;
    Intent i;
    String message, tomobilno, displayname = null;
    String[] messageto;
    SharedPreferences sh,idpreference;
    Notification noti;
    public int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager,myNotificationManager;




    int conservations, nofmsgs = 0;
    ArrayList<smsfetch> totalmsgs;
    Intent resultIntent;
    Uri notification;
    @SuppressLint("NewApi")
    public void displayNotification(Context context) {
        System.out.println("display notification");
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                context);
        totalmsgs=smsDb.getPushSMS();
        int totalsms=totalmsgs.size();
        int smscount=smsDb.getPush_uni_count();
        tomobilno=totalmsgs.get(0).getAddress();
        if(smscount==1){

            mBuilder.setContentTitle(tomobilno);

        }else{
            mBuilder.setContentTitle("Way2Inbox");
        }
Log.e("Display Times :","----------------PUSH NOTIF------------->");
        mBuilder.setContentText( totalsms+ " messages from " + smscount
                + " conservations");
        mBuilder.setTicker(totalsms + " new messages ");
        mBuilder.setSmallIcon(R.drawable.ic_launcher);

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        JSONArray jary = null;
        inboxStyle.setBigContentTitle("Way2Inbox");
        inboxStyle.setSummaryText(totalsms + " messages from " + smscount
                + " conservations");

        // jary = new JSONArray(msg);
        // String[] events = new String[jary.length()];
        for(smsfetch cn:totalmsgs){
            // events[i]=jary.getString(i);
                inboxStyle.addLine(cn.get_person() + ": " + cn.getMsg());
        }

        // events[0] = new String("1) Message for implicit intent");
        // events[1] = new String("2) big view Notification");
        // events[2] = new String("3) from javacodegeeks!");

        // Sets a title for the Inbox style big view

        // Moves events into the big view
        // for (int i=0; i < events.length; i++) {
        // ;
        // }
        mBuilder.setStyle(inboxStyle);

        // Increase notification number every time a new notification arrives
        // mBuilder.setNumber(jary.length());

        // when the user presses the notification, it is auto-removed
        mBuilder.setAutoCancel(true);

        // Creates an implicit intent

        // resultIntent.putExtra("MobileName", name);
        // resultIntent.putExtra("MobileNo", mobileno);
        if (smscount!= 1) {
            resultIntent = new Intent(context, Messages.class);
        } else {
            resultIntent = new Intent(context, ComposeSmsActivity.class);
            resultIntent.putExtra("MobileName", getContactName(tomobilno));
            resultIntent.putExtra("MobileNo", tomobilno);
        }
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(Messages.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_ONE_SHOT);
        mBuilder.setContentIntent(resultPendingIntent);
if(vibrate_status){
    mBuilder.setVibrate(new long[]{1000,1000,1000,1000});
}
           ringtone();
//        if(ringtonepath.equals(null)){
//         notification= RingtoneManager
//        .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//
//        }else{
//             notification = Uri.parse(ringtonepath);
//
//        }

       // mBuilder.setSound(notification);
        myNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        myNotificationManager.notify(0, mBuilder.build());
    }

    private void insertintosharedpref(String string) {
        SharedPreferences.Editor ed = sh.edit();
        ed.putString("msgs", string);
        ed.commit();
    }

    public String getContactName(String phoneNumber) {
        ContentResolver cr = context1.getContentResolver();
        Uri uri = Uri.withAppendedPath(
                ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(phoneNumber));
        Cursor cursor = cr.query(uri,
                new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME },
                null, null, null);
        if (cursor == null) {
            return null;
        }
        String contactName = null;
        if (cursor.moveToFirst()) {
            contactName = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
        } else {
            contactName = phoneNumber;
        }

        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }

        return contactName;
    }


    private void sendResultMessage(int data) {
        Intent intent = new Intent(Constants.FILTER);
        intent.putExtra(Constants.COMMAND, Constants.UPDATE_PROGRESS);
        intent.putExtra(Constants.DATA, data);
        LocalBroadcastManager.getInstance(context1).sendBroadcast(intent);
    }
    Ringtone r;
    public void ringtone(){


        try {
            if(ringtonepath.equals(null)){
                notification= RingtoneManager
                        .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            }else{
                notification = Uri.parse(ringtonepath);

            }
            r = RingtoneManager.getRingtone(context1, notification);
            r.play();
            new Handler().postDelayed(new Runnable() {

                // Using handler with postDelayed called runnable run method

                @Override
                public void run() {
                  r.stop();
                }
            }, 2 * 1000); // wait for 2 seconds
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean getPrefKeyValues(String key) {
		/* To get values from settings xml preference keys for booelans */
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(context1);
        return prefs.getBoolean(key, false);
    }
    private String getPrefKeyValues1(String key) {
		/* To get values from settings xml preference keys for booelans */
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(context1);
        return prefs.getString(key, null);
    }
}